package io.capsulode.tunnel.blockrepo.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;

/**
 * WebUtil
 *
 * @author lipei
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class WebUtil {

    public static void download(String url, Path dbPath) {
        try {
            log.debug("Downloading initial database: {}", url);
            URL website = new URL(url);
            URLConnection connection = website.openConnection();
            connection.setRequestProperty("User-Agent", "curl/7.64.1");
            try (ReadableByteChannel channel = Channels.newChannel(connection.getInputStream());
                 FileOutputStream fos = new FileOutputStream(dbPath.toFile())) {
                fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
            }
        } catch (IOException ex) {
            log.info("Download initial database failed", ex);
        }
    }
}
